package com.caifu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.caifu.pojo.SysUserToken;
import com.caifu.mapper.SysUserTokenMapper;
import com.caifu.service.SysUserTokenService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.caifu.util.TokenProcessor;
import com.caifu.util.Util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 * 用户token表 服务实现类
 * </p>
 *
 * @author szt
 * @since 2020-09-08
 */
@Service
public class SysUserTokenServiceImpl extends ServiceImpl<SysUserTokenMapper, SysUserToken> implements SysUserTokenService {

    @Resource
    private SysUserTokenMapper tokenMapper;

    @Override
    public String generateToken() throws Exception {
        try {
            String geToken="";
            while (true){
                String token = TokenProcessor.getInstance().generateToken(Util.currentDateTime(), true);
                SysUserToken tmpToken = tokenMapper.selectOne(new QueryWrapper<SysUserToken>().eq("TOKEN",token));
                if(tmpToken==null){
                    geToken = token;
                    break;
                }
            }
            if(StringUtils.isBlank(geToken)){
                throw new Exception("geToken null");
            }
            return geToken;
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("generateToken error");
        }
    }
}
